package com.itheima.bos.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.system.IMenuRepositroy;
import com.itheima.bos.dao.system.IPermissionRepository;
import com.itheima.bos.dao.system.IRoleRepository;
import com.itheima.bos.domain.system.Menu;
import com.itheima.bos.domain.system.Permission;
import com.itheima.bos.domain.system.Role;
import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.IRoleSerivce;

@Service
@Transactional
public class RoleServiceImpl implements IRoleSerivce {

	@Autowired
	private IRoleRepository roleRepository;

	@Autowired
	private IPermissionRepository permissionRepository;
	
	@Autowired
	private IMenuRepositroy menuRepositroy;

	@Override
	public List<Role> findByUser(User user) {

		// admin具有所有角色
		if (user.getUsername().equals("admin")) {
			return roleRepository.findAll();
		} else {
			return roleRepository.findByUser(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {

		return roleRepository.findAll();
	}

	@Override
	public void save(Role model, String[] permissionIds, String menuIds) {
		// 保存角色
		roleRepository.save(model);

		// 关联权限
		if (permissionIds != null) {
			for (String permissionId : permissionIds) {
				Permission permission = permissionRepository.findOne(Integer
						.parseInt(permissionId));
				model.getPermissions().add(permission);
			}
		}
		//关联菜单
		if (StringUtils.isNoneBlank(menuIds)) {
			String[] menuIdArray = menuIds.split(",");
			for (String menuId : menuIdArray) {
				Menu menu = menuRepositroy.findOne(Integer.parseInt(menuId));
				model.getMenus().add(menu);
			}
		}
	}

}
